package com.macro.mall.security.component;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.macro.mall.common.constants.Constants;
import com.macro.mall.security.util.HttpUtil;
import com.macro.mall.security.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT登录授权过滤器
 * Created by macro on 2018/4/26.
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String tokenPrefix = Constants.TOKEN_PREFIX;
        String authHeader = request.getHeader(Constants.TOKEN_HEADER);
        if (authHeader != null && authHeader.startsWith(tokenPrefix)) {
            String authToken = authHeader.substring(tokenPrefix.length());// The part after "Bearer "
            BaseUserDetails userDetail = jwtTokenUtil.getDpUserDetail(authToken);
            String username = userDetail.getUsername();
            LOGGER.info("checking username:{}", username);

            String id = userDetail.getId() + "";
            String nike = userDetail.getNike();
            String method = request.getMethod();
            MutableHttpServletRequest requestWrapper = new MutableHttpServletRequest(request);
            requestWrapper.putHeader(Constants.ID, id);
            requestWrapper.putHeader(Constants.TOKEN_NIKE, nike);
            requestWrapper.putHeader(Constants.USERNAME, username);
            String contentType = request.getContentType();

            if (StrUtil.isNotBlank(contentType)) {
                if (contentType.contains("application/json")) {
                    String bodyStr = HttpUtil.getPostData(request);
                    if (StrUtil.isBlank(bodyStr) || JSONUtil.isTypeJSONObject(bodyStr)) {
                        JSONObject entries = null;
                        if (StrUtil.isBlank(bodyStr)) {
                            entries = new JSONObject();
                        } else {
                            entries = JSONUtil.parseObj(bodyStr);
                        }
                        entries.putOpt(Constants.ID, id);
                        entries.putOpt(Constants.TOKEN_NIKE, nike);
                        entries.putOpt(Constants.USERNAME, username);
                        bodyStr = JSONUtil.toJsonStr(entries);
                    }
                    requestWrapper.setBodyJsonStr(bodyStr);
                }
                if ("GET".equals(method) || contentType.contains("multipart/form-data") || contentType.contains("application/x-www-form-urlencoded")) {
                    requestWrapper.addParameter(Constants.TOKEN_NIKE, nike);
                    requestWrapper.addParameter(Constants.ID, id);
                    requestWrapper.addParameter(Constants.USERNAME, username);
                }
            }

            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetail, null, userDetail.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                LOGGER.info("authenticated user:{}", username);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
            chain.doFilter(requestWrapper, response);
            return;
        }
        chain.doFilter(request, response);
    }
}
